package com.cxyzy.demo.widget

import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatTextView

class AnimTextView(context: Context, attrs: AttributeSet?) : AppCompatTextView(context, attrs) {

    init {
        post {
            layoutParams.rightMargin = -measuredWidth
        }
    }

    internal fun showAnim(during: Long = 1000) {
        visibility = View.VISIBLE
        val animator = ValueAnimator.ofInt(layoutParams.rightMargin, 0)
        animator.duration = during
        animator.addUpdateListener {
            val animValue: Int = it.animatedValue as Int
            layoutParams.rightMargin = animValue
            layoutParams = layoutParams
        }
        animator.start()
    }

    internal fun hideAnim(during: Long = 1000) {
        val animator = ValueAnimator.ofInt(layoutParams.rightMargin, -measuredWidth)
        animator.duration = during
        animator.addUpdateListener {
            val animValue: Int = it.animatedValue as Int
            layoutParams.rightMargin = animValue
            layoutParams = layoutParams
        }
        animator.start()
    }

    override fun getLayoutParams(): ViewGroup.MarginLayoutParams {
        return super.getLayoutParams() as ViewGroup.MarginLayoutParams
    }
}